﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Contexts;

namespace QuoteDAL
{
    public class QuoteDAL
    {
        /// <summary>
        /// 从网络上获取股票的当日收盘行情
        /// </summary>
        /// <param name="stock"></param>
        /// <returns></returns>
        private Quote.Quote GetQuote(Quote.Stock stock)
        {
            //http://hq.sinajs.cn/list=sh601006
            //http://hq.sinajs.cn/list=s_sz399001     深圳成指
            //http://hq.sinajs.cn/list=s_sh000001     上证指数
            string url = "http://hq.sinajs.cn/list=" + stock.Market + stock.Code;
            string content = HttpDAL.ReadUrlContent(url, "utf-8");
            Quote.Quote quote = new Quote.Quote();
            if (content.IndexOf(",") > 0)
            {
                string[] contents = content.Split(new char[] { ',' });
                quote.Bug = Convert.ToDouble(contents[6]);
                quote.Close = Convert.ToDouble(contents[3]);
                quote.Coast = Convert.ToDouble(contents[9]);
                quote.High = Convert.ToDouble(contents[4]);
                quote.Low = Convert.ToDouble(contents[5]);
                quote.Open = Convert.ToDouble(contents[1]);
                quote.Pdate = Convert.ToDateTime(contents[30]);
                quote.Sell = Convert.ToDouble(contents[7]);
                quote.StockId = stock.Id;
                quote.Volumn = Convert.ToDouble(contents[8]);
                quote.YesterdayClose = Convert.ToDouble(contents[2]);
            }
            else
            {
                quote.Bug = -1;
                quote.Close = -1;
                quote.Coast = -1;
                quote.High = -1;
                quote.Low = -1;
                quote.Open = -1;
                quote.Pdate = Convert.ToDateTime(DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day);
                quote.Sell = -1;
                quote.StockId = stock.Id;
                quote.Volumn = -1;
                quote.YesterdayClose = -1;
            }
            return quote;
        }
        /// <summary>
        /// 从网络上获取当日收盘后的所有股票行情
        /// </summary>
        public void GetQuotes()
        {
            DB.DBManager db = new DB.DBManager();
            var stocks = db.Stocks.ToList();
            foreach (Quote.Stock stock in stocks)
            {
                Quote.Quote quote = GetQuote(stock);
                var queryExist = db.Quotes.Where(a => a.StockId == quote.StockId).Where(a => a.Pdate.Year == quote.Pdate.Year).Where(a => a.Pdate.Month == quote.Pdate.Month).Where(a => a.Pdate.Day == quote.Pdate.Day).ToList();
                if (queryExist.Count == 0)
                {
                    db.Quotes.Add(quote);
                }
            }
            db.SaveChanges();
            db.Dispose();
        }

        /// <summary>
        /// 从通达信上面导出的历史K线文件上读取历史行情
        /// </summary>
        public void InitHistoryQuote()
        {
            DB.DBManager db = new DB.DBManager();
            var stocks = db.Stocks.ToList();
            db.Dispose();
            foreach (Quote.Stock stock in stocks)
            {
                if (stock.Id > 1048)
                {
                    GetStockHistoryQuote(stock.Id, @"D:\Program Files\sw2000\T0002\export\" + stock.Code + ".TXT");
                }
            }



        }
        private void GetStockHistoryQuote(int stockId, string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                DB.DBManager db = new DB.DBManager();
                System.IO.FileStream file = System.IO.File.Open(filePath, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
                System.IO.StreamReader reader = new System.IO.StreamReader(file);
                int line = 0;
                while (!reader.EndOfStream)
                {
                    string str = reader.ReadLine();
                    if (line > 1)
                    {
                        Quote.Quote quote = new Quote.Quote();
                        if (str.IndexOf(",") > 0)
                        {
                            string[] strs = str.Split(new char[] { ',' });
                            quote.Pdate = Convert.ToDateTime(strs[0]);
                            quote.StockId = stockId;
                            quote.Close = Convert.ToDouble(strs[4]);
                            quote.High = Convert.ToDouble(strs[2]);
                            quote.Low = Convert.ToDouble(strs[3]);
                            quote.Open = Convert.ToDouble(strs[1]);
                            quote.Volumn = Convert.ToDouble(strs[5]);
                            quote.Bug = 0f;
                            quote.Coast = Convert.ToDouble(strs[6]);
                            quote.Sell = 0f;
                            quote.YesterdayClose = 0f;
                            db.Quotes.Add(quote);
                            //db.SaveChanges();

                        }
                    }
                    line++;
                }
                db.SaveChanges();
            }
        }

        /// <summary>
        /// 获取历史数据的分析数据
        /// </summary>
        /// <param name="stockId"></param>
        /// <param name="filePath"></param>
        /// <param name="db"></param>
        public void InitStockHistoryQuoteAdv()
        {
            DB.DBManager db = new DB.DBManager();
            var stocks = db.Stocks.ToList();
            db.Dispose();
            foreach (Quote.Stock stock in stocks)
            {
                DB.DBManager db2 = new DB.DBManager();
                //Context.Configuration.AutoDetectChangesEnabled = false;

                if (stock.Id > 921)
                {
                    var quotes = db2.Quotes.Where(a => a.StockId == stock.Id).OrderBy(a => a.Pdate).ToList();
                    foreach (Quote.Quote quote in quotes)
                    {
                        Quote.QuoteSummary summary = new Quote.QuoteSummary();
                        summary.Pdate = quote.Pdate;
                        summary.StockId = quote.StockId;
                        summary.Close = quote.Close;
                        summary.High = quote.High;
                        summary.Low = quote.Low;
                        summary.Open = quote.Open;
                        summary.Volumn = quote.Volumn;

                        summary.MA10 = Math.Round((quotes.Where(a => a.Pdate <= summary.Pdate).Where(a => a.Close != -1).OrderByDescending(a => a.Pdate).Take(10).Average(a => a.Close)), 2);
                        summary.MA20 = Math.Round((quotes.Where(a => a.Pdate <= summary.Pdate).Where(a => a.Close != -1).OrderByDescending(a => a.Pdate).Take(20).Average(a => a.Close)), 2);
                        summary.MA5 = Math.Round((quotes.Where(a => a.Pdate <= summary.Pdate).Where(a => a.Close != -1).OrderByDescending(a => a.Pdate).Take(5).Average(a => a.Close)), 2);
                        summary.MA60 = Math.Round((quotes.Where(a => a.Pdate <= summary.Pdate).Where(a => a.Close != -1).OrderByDescending(a => a.Pdate).Take(60).Average(a => a.Close)), 2);

                        var yesterdayquote = quotes.Where(a => a.Pdate < summary.Pdate).Where(a => a.Close != -1).OrderByDescending(a => a.Pdate);
                        double yesterdayclose = 1;
                        if (yesterdayquote.Count() > 0)
                        {
                            yesterdayclose = yesterdayquote.First().Close;
                        }

                        summary.RaiseAmount = Math.Round(summary.Close - yesterdayclose, 2);
                        if (yesterdayclose == 0)
                        {
                            yesterdayclose = 1;
                        }
                        summary.RaiseRate = Math.Round(summary.RaiseAmount * 100 / yesterdayclose, 2);
                        //if()
                        summary.Swing = Math.Round((summary.High - summary.Low) * 100 / yesterdayclose, 2);
                        db2.QuoteSummarys.Add(summary);
                    }
                    quotes = null;
                }
                db2.SaveChanges();
                db2.Dispose();
            }

        }
    }
}
